#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
流程图识别程序安装脚本
"""

import os
import sys
import subprocess
import platform
import urllib.request
import zipfile
import shutil

def print_banner():
    """打印安装横幅"""
    print("=" * 60)
    print("          流程图识别程序 - 环境安装脚本")
    print("=" * 60)
    print("本脚本将帮助您安装流程图识别程序所需的所有依赖")
    print("=" * 60)

def check_python_version():
    """检查Python版本"""
    print("1. 检查Python版本...")
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print(f"❌ Python版本过低: {version.major}.{version.minor}")
        print("   需要Python 3.8或更高版本")
        return False
    else:
        print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
        return True

def install_python_packages():
    """安装Python依赖包"""
    print("\n2. 安装Python依赖包...")
    try:
        # 升级pip
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        
        # 安装依赖包
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✅ Python依赖包安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Python依赖包安装失败: {e}")
        return False

def check_tesseract():
    """检查Tesseract OCR是否已安装"""
    print("\n3. 检查Tesseract OCR...")
    try:
        import pytesseract
        version = pytesseract.get_tesseract_version()
        print(f"✅ Tesseract已安装，版本: {version}")
        return True
    except Exception as e:
        print(f"❌ Tesseract未安装或配置错误: {e}")
        return False

def install_tesseract_windows():
    """在Windows上安装Tesseract"""
    print("\n4. 在Windows上安装Tesseract OCR...")
    
    # Tesseract下载URL
    tesseract_url = "https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-5.3.1.20230401.exe"
    installer_path = "tesseract_installer.exe"
    
    try:
        print("   下载Tesseract安装程序...")
        urllib.request.urlretrieve(tesseract_url, installer_path)
        
        print("   运行安装程序...")
        print("   请在弹出的安装窗口中完成Tesseract的安装")
        print("   建议安装到默认路径: C:\\Program Files\\Tesseract-OCR\\")
        
        subprocess.run([installer_path], shell=True)
        
        # 清理安装文件
        if os.path.exists(installer_path):
            os.remove(installer_path)
        
        print("✅ Tesseract安装完成")
        return True
        
    except Exception as e:
        print(f"❌ Tesseract安装失败: {e}")
        print("   请手动下载并安装Tesseract:")
        print("   https://github.com/UB-Mannheim/tesseract/wiki")
        return False

def install_tesseract_linux():
    """在Linux上安装Tesseract"""
    print("\n4. 在Linux上安装Tesseract OCR...")
    
    system = platform.system().lower()
    
    try:
        if system == "linux":
            # 检测包管理器
            if os.path.exists("/etc/debian_version"):
                # Debian/Ubuntu
                subprocess.check_call(["sudo", "apt-get", "update"])
                subprocess.check_call(["sudo", "apt-get", "install", "-y", 
                                     "tesseract-ocr", "tesseract-ocr-chi-sim"])
            elif os.path.exists("/etc/redhat-release"):
                # CentOS/RHEL/Fedora
                subprocess.check_call(["sudo", "yum", "install", "-y", 
                                     "tesseract", "tesseract-langpack-chi-sim"])
            else:
                print("   无法自动检测包管理器，请手动安装Tesseract")
                return False
            
            print("✅ Tesseract安装完成")
            return True
        else:
            print(f"   不支持的操作系统: {system}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"❌ Tesseract安装失败: {e}")
        return False

def install_tesseract_macos():
    """在macOS上安装Tesseract"""
    print("\n4. 在macOS上安装Tesseract OCR...")
    
    try:
        # 检查是否安装了Homebrew
        subprocess.check_call(["brew", "--version"], stdout=subprocess.DEVNULL)
        
        # 安装Tesseract
        subprocess.check_call(["brew", "install", "tesseract", "tesseract-lang"])
        
        print("✅ Tesseract安装完成")
        return True
        
    except subprocess.CalledProcessError:
        print("❌ 需要先安装Homebrew")
        print("   请访问 https://brew.sh 安装Homebrew")
        return False

def test_installation():
    """测试安装是否成功"""
    print("\n5. 测试安装...")
    
    try:
        # 测试Python包
        import cv2
        import numpy as np
        import pytesseract
        import networkx as nx
        from PIL import Image
        import matplotlib.pyplot as plt
        
        print("✅ Python依赖包测试通过")
        
        # 测试Tesseract
        version = pytesseract.get_tesseract_version()
        print(f"✅ Tesseract测试通过，版本: {version}")
        
        # 测试程序模块
        from src.preprocessing import ImageProcessor
        from src.detection import NodeDetector
        from src.connection import ConnectionDetector
        from src.ocr import TextRecognizer
        from src.analysis import LogicAnalyzer
        from src.output import JSONGenerator
        
        print("✅ 程序模块导入测试通过")
        
        return True
        
    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        return False
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def create_sample_test():
    """创建示例测试"""
    print("\n6. 创建示例测试...")
    
    try:
        # 运行示例脚本
        subprocess.check_call([sys.executable, "example.py"])
        print("✅ 示例测试通过")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 示例测试失败: {e}")
        return False

def main():
    """主函数"""
    print_banner()
    
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 安装Python依赖包
    if not install_python_packages():
        sys.exit(1)
    
    # 检查Tesseract
    tesseract_installed = check_tesseract()
    
    if not tesseract_installed:
        system = platform.system().lower()
        
        if system == "windows":
            install_tesseract_windows()
        elif system == "linux":
            install_tesseract_linux()
        elif system == "darwin":
            install_tesseract_macos()
        else:
            print(f"不支持的操作系统: {system}")
            print("请手动安装Tesseract OCR")
    
    # 测试安装
    if not test_installation():
        print("\n❌ 安装测试失败，请检查错误信息")
        sys.exit(1)
    
    # 创建示例测试
    create_sample_test()
    
    print("\n" + "=" * 60)
    print("🎉 安装完成！")
    print("=" * 60)
    print("现在您可以使用以下命令处理流程图：")
    print("python flowchart_recognizer.py --image_path \"your_flowchart.png\"")
    print("\n更多使用说明请查看 README.md 文件")
    print("=" * 60)

if __name__ == "__main__":
    main() 